package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        //jdbc查询数据库操作，m1方法
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //1、 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、获取链接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8",
                    "root", "123456");


            //3、编写sql语句
            String sql = "select * from sys_user";

            //4、预处理sql
            preparedStatement = conn.prepareStatement(sql);
            //5、设置参数

            //6、执行sql语句
            resultSet = preparedStatement.executeQuery();

            //7、查询遍历结果或增删改判断是否正确
            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
                users.add(user);
            }
            return users;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (conn != null) {
                    conn.close();
                }

            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
